package cn.caplike.demo.rabbitmq.api.flowlimiting;

import cn.caplike.demo.rabbitmq.api.Application;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author LiKe
 * @version 1.0.0
 * @date 2020-02-19 12:18
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Application.RABBITMQ_HOST);
        connectionFactory.setPort(Application.RABBITMQ_PORT);
        connectionFactory.setVirtualHost("/");

        // 通过链接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 通过连接创建一个 Channel
        Channel channel = connection.createChannel();

        final String exchangeName = "test_qos_exchange";
        final String routingKey = "qos.*";
        final String queueName = "test_qos_queue";
        channel.exchangeDeclare(exchangeName, "topic", false);
        channel.queueDeclare(queueName, false, false, true, null);
        channel.queueBind(queueName, exchangeName, routingKey);

        System.out.println("Waiting for message ...");
        // global false 在 consumer 层显示, true channel 层面
        // 一次性只接收 1 条消息
        channel.basicQos(0, 1, false);
        // 消费端限流不能设置为自动签收 autoAck -> false
        channel.basicConsume(queueName, false, new MyConsumer(channel));
    }
}
